package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
)

// 共用一个client，适用于请求比较频繁的场合
var (
	client = http.Client{
		Transport: &http.Transport{
			DisableKeepAlives: true, // 禁止短连接，保持长连接
		},
	}
)

func main() {
	/*
		resp, err := http.Get("http://127.0.0.1:9999/test2?name=yayako&age=22")
		if err != nil {
			fmt.Println("get msg from server failed, err:", err)
			return
		}
	*/

	data := url.Values{}
	urlObj, _ := url.Parse("http://127.0.0.1:9999/test2")
	data.Set("name", "yayako")
	data.Set("age", "22")
	urlObj.RawQuery = data.Encode() // 编码之后的url
	fmt.Println("url:", urlObj.RawQuery)
	request, err := http.NewRequest("GET", urlObj.String(), nil)
	if err != nil {
		fmt.Println("create new request failed, err:", err)
		return
	}

	/*
		// 常规client
		response, err := http.DefaultClient.Do(request)
		if err != nil {
			fmt.Println("get msg from server failed, err:", err)
			return
		}
	*/

	// 自定义client
	/*
		// 适用于请求不是特别频繁的场合，连接用完就关闭该链接
		client := http.Client{
			Transport: &http.Transport{
				DisableKeepAlives: true,
			},
		}
	*/
	response, err := client.Do(request)
	if err != nil {
		fmt.Println("get msg from server failed, err:", err)
		return
	}

	defer response.Body.Close() // 必须关闭回复的主体

	bytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println("read body failed, err:", err)
		return
	}
	fmt.Println(string(bytes))
}
